local functions = require("packages.ads-universe.functions")

local ads__quede = fk.CreateSkill {
  name = "ads__quede",
}

ads__quede:addEffect("active", {
  anim_type = "offensive",
  prompt = "#ads__quede-active",
  card_num = 0,
  target_num = 1,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and to_select ~= player and to_select:getHandcardNum() > 0
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local target = effect.tos[1]
    local cards = room:askToChooseCards(player, {
      target = target,
      min = 1,
      max = 2,
      flag = "h",
      skill_name = ads__quede.name,
    })
    if #cards == 0 then return end
    
    local marks = target:getMark("_ads__quede_cards-phase")
    room:obtainCard(player, cards, false, fk.ReasonGive, player, ads__quede.name)
    room:addPlayerMark(target, "_ads__quede_cards-phase", #cards)
    if marks < 2 and marks + #cards >= 2 and not target.dead then
      room:loseHp(target, 1, ads__quede.name)
    end
  end,
})

Fk:loadTranslationTable{
  ["$ads__quede1"] = "以德服人。",
  ["$ads__quede2"] = "唯贤唯德，能服于人。",
  ["ads__quede"] = "缺德",
  [":ads__quede"] = "出牌阶段，你可以将任意其他角色至多2张手牌分配给你。其他角色于本阶段内以此法给出的手牌首次达到两张或更多后，其失去1点体力。",
  ["#ads__quede-active"] = "发动 缺德，夺取其他角色的手牌",
  ["#ads__quede-choose"] = "缺德：选择要夺取的手牌（至多2张）",
}

ads__quede:addAI({
  think = function(self, ai)
    local player = ai.player
    local room = player.room
    
    local enemies = table.filter(room.alive_players, function(p)
      return p ~= player and functions.isEnemy(player, p) and p:getHandcardNum() > 0
    end)
    
    if #enemies == 0 then return "" end
    
    table.sort(enemies, function(a, b)
      return a:getHandcardNum() > b:getHandcardNum()
    end)
    
    local target = enemies[1]
    local handcard_num = target:getHandcardNum()
    local current_marks = target:getMark("_ads__quede_cards-phase")
    local to_take = math.min(2, handcard_num)
    local damage_benefit = (current_marks < 2 and current_marks + to_take >= 2) and 2 or 0
    local total_benefit = to_take + damage_benefit
    
    if total_benefit <= 0 then return "" end
    
    return { targets = { target } }, total_benefit
  end,
  
  think_card_chosen = function(self, ai, target, flag, prompt)
    local handcards = target:getCardIds(Player.Hand)
    if #handcards == 0 then return -1, 0 end
    
    local current_marks = target:getMark("_ads__quede_cards-phase")
    local to_take = math.min(2, #handcards)
    
    local damage_benefit = (current_marks < 2 and current_marks + to_take >= 2) and 2 or 0
    local total_benefit = to_take + damage_benefit
    
    return handcards[1], total_benefit
  end,
})


return ads__quede
